/*
 * @Description 
 * @Autor lzhiqiang
 * @Date 2023-03-08 16:45:49
 * @LastEditors lzhiqiang
 * @LastEditTime 2023-03-10 22:24:15
 */
#include "hook.h"
#include "johnsonli.h"
#include "iomanager.h"

#include <sys/socket.h>
#include <unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <sys/types.h>

johnsonli::Logger::ptr g_logger = LOG_ROOT();

void test01()
{
    johnsonli::IOManager iom(1);

    iom.schedule([](){
        sleep(2);
        LOG_INFO(g_logger) << "sleep 2";
    });

    
    iom.schedule([](){
        sleep(3);
        LOG_INFO(g_logger) << "sleep 3";
    });


    LOG_INFO(g_logger) << "sleep";

}

void test_hook()
{
    //std::cout << "1111" << std::endl;
    int cfd = socket(AF_INET, SOCK_STREAM, 0);
    // fcntl(cfd, F_SETFL, O_NONBLOCK);

    sockaddr_in addr;
    memset(&addr, 0, sizeof(sockaddr_in));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    inet_pton(AF_INET, "112.80.248.75", &addr.sin_addr.s_addr);

    LOG_INFO(g_logger) << "begin connect";
    int rt = connect(cfd, (const sockaddr*)&addr, sizeof(addr));
    LOG_INFO(g_logger) << "connect rt=" << rt << " errno=" << errno;

    if(rt)
    {
        return;
    }

    const char data[] = "GET / HTTP/1.0\r\n\r\n";
    rt = send(cfd, data, sizeof(data), 0);
    LOG_INFO(g_logger) << "send rt=" << rt << " errno=" << errno;

    if(rt <= 0)
    {
        return;
    }

    std::string buff;
    buff.resize(4096);
    rt = recv(cfd, &buff[0], buff.size(), 0);
    LOG_INFO(g_logger) << "recv rt=" << rt << " errno=" << errno;

    if(rt <= 0)
    {
        return;
    }

    buff.resize(rt);
    LOG_INFO(g_logger) << buff;

}

int main()
{
    //std::cout<<"1111"<<std::endl;
    //test_hook();
    johnsonli::IOManager iom;
    iom.schedule(test_hook);
    return 0;
}